package com.genersoft.iot.vmp.conf;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

/**
 * 数据库初始化组件
 * 在应用启动时检查并创建缺失的数据库表
 */
//@Component  // 暂时禁用自动初始化
public class DatabaseInitializer implements ApplicationRunner {

    private static final Logger log = LoggerFactory.getLogger(DatabaseInitializer.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("[数据库初始化] 开始检查数据库表结构...");

        try {
            // 检查核心表是否存在
            if (!checkCoreTablesExist()) {
                log.warn("[数据库初始化] 检测到核心表缺失，需要执行完整的数据库初始化");
                log.warn("[数据库初始化] 请手动执行以下SQL脚本来初始化数据库：");
                log.warn("[数据库初始化] mysql_init_script_complete.sql");
                log.warn("[数据库初始化] 或者使用命令：mysql -h 127.0.0.1 -P 3306 -u root -p12345678 < mysql_init_script_complete.sql");
                return;
            }

            // 检查并创建 wvp_record_plan 表
            createRecordPlanTableIfNotExists();

            // 检查并创建 wvp_record_plan_item 表
            createRecordPlanItemTableIfNotExists();

            log.info("[数据库初始化] 数据库表结构检查完成");
        } catch (Exception e) {
            log.error("[数据库初始化] 数据库表结构检查失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 检查核心表是否存在
     */
    private boolean checkCoreTablesExist() {
        try {
            String[] coreTables = {"wvp_media_server", "wvp_platform", "wvp_device", "wvp_device_channel"};
            for (String tableName : coreTables) {
                String checkTableSql = "SELECT COUNT(*) FROM information_schema.tables " +
                        "WHERE table_schema = DATABASE() AND table_name = ?";
                Integer count = jdbcTemplate.queryForObject(checkTableSql, Integer.class, tableName);
                if (count == null || count == 0) {
                    log.warn("[数据库初始化] 核心表 {} 不存在", tableName);
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            log.error("[数据库初始化] 检查核心表失败: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 创建 wvp_record_plan 表（如果不存在）
     */
    private void createRecordPlanTableIfNotExists() {
        try {
            // 检查表是否存在
            String checkTableSql = "SELECT COUNT(*) FROM information_schema.tables " +
                    "WHERE table_schema = DATABASE() AND table_name = 'wvp_record_plan'";
            Integer count = jdbcTemplate.queryForObject(checkTableSql, Integer.class);
            
            if (count == null || count == 0) {
                log.info("[数据库初始化] 创建 wvp_record_plan 表...");
                String createTableSql = "CREATE TABLE wvp_record_plan (" +
                        "id INT AUTO_INCREMENT PRIMARY KEY," +
                        "snap TINYINT(1) DEFAULT 0," +
                        "name VARCHAR(255) NOT NULL," +
                        "create_time VARCHAR(50)," +
                        "update_time VARCHAR(50)" +
                        ")";
                jdbcTemplate.execute(createTableSql);
                log.info("[数据库初始化] wvp_record_plan 表创建成功");
            } else {
                log.info("[数据库初始化] wvp_record_plan 表已存在");
            }
        } catch (Exception e) {
            log.error("[数据库初始化] 创建 wvp_record_plan 表失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 创建 wvp_record_plan_item 表（如果不存在）
     */
    private void createRecordPlanItemTableIfNotExists() {
        try {
            // 检查表是否存在
            String checkTableSql = "SELECT COUNT(*) FROM information_schema.tables " +
                    "WHERE table_schema = DATABASE() AND table_name = 'wvp_record_plan_item'";
            Integer count = jdbcTemplate.queryForObject(checkTableSql, Integer.class);
            
            if (count == null || count == 0) {
                log.info("[数据库初始化] 创建 wvp_record_plan_item 表...");
                String createTableSql = "CREATE TABLE wvp_record_plan_item (" +
                        "id INT AUTO_INCREMENT PRIMARY KEY," +
                        "start INT," +
                        "stop INT," +
                        "week_day INT," +
                        "plan_id INT," +
                        "create_time VARCHAR(50)," +
                        "update_time VARCHAR(50)" +
                        ")";
                jdbcTemplate.execute(createTableSql);
                log.info("[数据库初始化] wvp_record_plan_item 表创建成功");
            } else {
                log.info("[数据库初始化] wvp_record_plan_item 表已存在");
            }
        } catch (Exception e) {
            log.error("[数据库初始化] 创建 wvp_record_plan_item 表失败: {}", e.getMessage(), e);
        }
    }
}
